/*初始化音视频*/
define(['js/plugins/chat/meeting/JRTCSDK-H5', 'js/lib/async.min', 'js/plugins/chat/chat.common', 'js/plugins/chat/i18n/chat.' + $E.lang, 'js/plugins/chat/jquery.rateyo.min'], function (JRTCSDK, async, $COMM, i18n) {
    var chatServerAddr,
        Tools = $COMM.Tools,
        tools,
        roomId,
        sessionId,
        audioIconAreaElement,
        videoIconAreaElement,
        chatSendMessage
    //调用服务接口
    var callService = function (params, retry) {
        if (params && params.url) {
            params.url = tools.chatServerAddr + "/" + params.url;
        }
        return tools.callService(params, (retry ? 0 : undefined));
    };

    let {
        JRTCClient,
        JRTCClientInitParam,
        JRTCClientLoginParam,
        JRTCClientCallback,
        ClientState,
        JRTCMediaDevice,
        RenderType,
        JRTCMediaDeviceVideoCanvas,
        JRTCRoom,
        JRTCRoomInitParam,
        JRTCRoomJoinParam,
        JRTCRecordRemoteParam,
        StompSocketAuthType,
        RoomState,
        JRTCRoomParticipant,
        RemoteRecordState,
        JRTCVersion,
        JRTCTracking,
        StorageManager,
        IntelligentMergeMode,
        VideoMergeMode,
        ScsMergeMode,
        JRTCLog,
        VideoDefinition,
        NetStatus,
        MediaType
    } = JRTCSDK;
    juFengApiPortUrl=''
    clientEnv = {
        server: '',
        appKey: '',
        token: '',
        tokenType: 'jrtc_access'
    },
        //房间的环境参数
        roomEnv = {
            server: '',
        },
        client = null,
        clienstState = ClientState.NOT_INIT,
        // 是否初始化,true为销毁

        clientStateText = '未登录',
        // 是否登录

        version = '',
        mediaDevice = null,
        cameraList = [],
        microphoneList = [],
        localCanvas = null,
        localAuido = null,
        // 音量 progress map
        volumeMap = {},
        renderTypeMap = [
            {'label': 'FullContent', value: RenderType.RENDER_FULL_CONTENT},
            {'label': 'FullScreen', value: RenderType.RENDER_FULL_SCREEN},
        ],
        // 渲染模式
        renderType = RenderType.RENDER_FULL_SCREEN,
        room = null,
        roomCallback = null,
        roomStatus = 'idle',
        roomStateText = '空闲',
        roomState = RoomState.IDLE,

        maxResolutionMap = [
            {'label': '360p', value: 0},
            {'label': '720p', value: 1},
            {'label': '1080p', value: 2},
        ],

        securityTypeMap = [
            {'label': '不加密', value: 0},
            {'label': 'SRTP', value: 1},
            {'label': 'SM4', value: 2},
        ],

        videoEncodeTypeMap = [
            {'label': 'H264', value: 0},
            {'label': 'AV1', value: 1},
        ],

        audioEncodeTypeMap = [
            {'label': 'OPUS', value: 0},
            {'label': 'PCMA', value: 1},
            {'label': 'PCMU', value: 2},
        ],

        recordMergeModeMap = [
            {'label': '初始值', value: VideoMergeMode.INIT},
            {'label': '自定义布局', value: VideoMergeMode.CUSTOM_LAYOUT},
            {'label': '智能分屏', value: VideoMergeMode.INTELLIGENT_LAYOUT},
        ],
        intelligentMergeModeMap = [
            {'label': '初始值', value: IntelligentMergeMode.INIT},
            {'label': '自由布局', value: IntelligentMergeMode.FREE_LAYOUT},
            {'label': '矩形布局', value: IntelligentMergeMode.RECT_LAYOUT},
            {'label': '大小屏放大2倍', value: IntelligentMergeMode.BIG_SMALL_X2},
            {'label': '大小屏放大3倍', value: IntelligentMergeMode.BIG_SMALL_X3},
            {'label': '大小屏放大4倍', value: IntelligentMergeMode.BIG_SMALL_X4},
            {'label': '大小屏放大5倍', value: IntelligentMergeMode.BIG_SMALL_X5},
            {'label': '大小屏放大6倍', value: IntelligentMergeMode.BIG_SMALL_X6},
            {'label': '大小屏放大7倍', value: IntelligentMergeMode.BIG_SMALL_X7},
            {'label': '大小屏放大8倍', value: IntelligentMergeMode.BIG_SMALL_X8},
            {'label': '大小屏放大9倍', value: IntelligentMergeMode.BIG_SMALL_X9},
            {'label': '大小屏放大10倍', value: IntelligentMergeMode.BIG_SMALL_X10},
            {'label': '大小屏放大到顶部', value: IntelligentMergeMode.BIG_SMALL_TOP},
            {'label': '大小屏放大到底部', value: IntelligentMergeMode.BIG_SMALL_BOTTOM},
            {'label': '绝对等分模式', value: IntelligentMergeMode.DIVIDE_LAYOUT},
            {'label': '绝对等分模式不带图像角度', value: IntelligentMergeMode.DIVIDE_LAYOUT_NO_ANGLE},
        ],
        scsMergeModeMap = [
            {'label': '初始值', value: ScsMergeMode.INIT},
            {'label': '屏幕共享', value: ScsMergeMode.SCREEN_SHARE},
            {'label': '将屏幕共享和所有视频内容合并，所有视频不覆盖屏幕共享', value: ScsMergeMode.PLATE_FORM},
            {'label': '将屏幕共享和所有视频内容合并，所有视频覆盖在屏幕共享', value: ScsMergeMode.PLATE_FORM_COVER},
            {'label': '将屏幕共享和焦点视频内容合并', value: ScsMergeMode.SPEAKER},
            {'label': '忽略屏幕共享', value: ScsMergeMode.WITHOUT_SCREEN_SHARE},
        ],
        onlineMessage = {
            content: '',
            userId: ''
        },
        mediaSettings = {
            isSelfDefined: false,
            maxResolution: 0,
            svcResolution: '1 90 70 180 180 360 480 720 1350',
            captureResolution: 1,
            frameRate: 24
        },
        joinSettings = {
            userId: $E.staff.id,
            displayName: '',
            roomId: '',
            password: '',
            capacity: 6,
            enableRecord: true,
            isMultiStream: false,
            maxResolution: 0,
            uploadLocalVideo: true,
            uploadLocalAudio: true,
            wholeRatio: 1.7777,
            securityType: 0,
            smoothMode: true,
            heartbeatTime: 20,
            heartbeatTimeout: 60,
            videoEncodeType: 0,
            audioEncodeType: 0,
            extraInfo: '',
            captureWidth: 360,
            captureHeight: 640,
            frameRate: 24,
            videoDefinition: 0, // VideoDefinition
            businessId: '' //业务流水号
        },

        roomSettings = {
            currentCamera: null,
            currentMic: null,
            remoteRecordSettings: {
                recordVideo: true,
                mergeMode: VideoMergeMode.INIT, // 合并模式
                intelligentMergeMode: IntelligentMergeMode.INIT, // 智能分屏无屏幕共享
                scsMergeMode: ScsMergeMode.INIT, // 智能分屏带屏幕共享
                frameRate: 24,
                bitrate: 15,
                videoWidth: 640,
                videoHeight: 360,
                waterMark: '',
                extraInfo: '',
                layoutType: '',
                layoutArray: '',
                fileName: 'H5_record',
                splitFileSize: -1,
            },
            queryRoom: {
                roomId: null,
            },
            sendMessage: {
                type: '',
                content: '',
                userId: '',
            },
            participants: [],
            screenShareUserId: '',
            recordState: RemoteRecordState.NONE,
            enableStopRecord: false,
            ratio: 0.5625,

        },

        publishingVideo = false, // 是否正在视频推流
        publishingAudio = false, // 是否正在音频推流

        screenShareCanvas = null,

        /**
         * Stats
         */
        statsInfo = '',
        statsInternalKey = null,

        /**
         * storage
         */
        storage = null,

        /**
         * toast
         */
        toastList = [],

        // 日志存储
        logStore = false,
        sessionId = ''
        videoUrlIndex = 0


    var Meet = {
        init: function (sendMsg,chatServerUrl, initParam, meetSessionId, userName, container, acceptRoomId) {
            clientEnv.server =initParam.juFengClientUrl
            clientEnv.appKey =initParam.juFengAppKey
            roomEnv.server =initParam.juFengRoomUrl
            juFengApiPortUrl = initParam.juFengApiPortUrl
            chatSendMessage = sendMsg
            chatServerAddr = chatServerUrl
            tools = new Tools(chatServerAddr, 5);
            sessionId = meetSessionId

            version = JRTCVersion.getSDKVersion();

            storage = new StorageManager();

            const settingFormData = storage.get('settingFormData_webrtc-room-sdk');

            if (settingFormData) {
                Object.entries(settingFormData)
                    .forEach((entity) => this[entity[0]] = entity[1]);
            }

            window.addEventListener('beforeunload', (ev) => {
                const {roomSettings, joinSettings, mediaSettings, clientEnv, roomEnv, logStore} = this;

                storage.set('settingFormData_webrtc-room-sdk', {
                    roomSettings,
                    joinSettings,
                    mediaSettings,
                    clientEnv,
                    roomEnv,
                    logStore
                });

                ev.preventDefault();
                ev.returnValue = '';
                return '';
            });

            window.addEventListener('pagehide', (ev) => {
                const {roomSettings, joinSettings, mediaSettings, clientEnv, roomEnv, logStore} = this;

                storage.set('settingFormData_webrtc-room-sdk', {
                    roomSettings,
                    joinSettings,
                    mediaSettings,
                    clientEnv,
                    roomEnv,
                    logStore
                });

                ev.preventDefault();
                ev.returnValue = '';
                return '';
            });

            if (!joinSettings.captureWidth | joinSettings.captureWidth <= 0) {
                joinSettings.captureWidth = 360;
            }

            if (!joinSettings.captureHeight | joinSettings.captureHeight <= 0) {
                joinSettings.captureWidth = 640;
            }

            if (!joinSettings.frameRate | joinSettings.frameRate <= 0) {
                joinSettings.frameRate = 24;
            }
            isInitialized = false
            isLogin = false
            isJoined = false
            client = null,
            mediaDevice = null,
            cameraList = [],
            microphoneList = [],
            localCanvas = null,
            localAuido = null,
            roomCallback = null,
            roomStatus = 'idle',
            roomStateText = '空闲',
            publishingVideo = false, // 是否正在视频推流
            publishingAudio = false, // 是否正在音频推流

            screenShareCanvas = null,

            /**
             * Stats
             */
            statsInfo = '',
            statsInternalKey = null,

            /**
             * storage
             */
            storage = null,

            /**
             * toast
             */
            toastList = [],
            joinSettings.roomId =acceptRoomId? acceptRoomId : generateUniqueString(9);
            console.log('joinSettings.roomId',joinSettings.roomId)
            // console.log('initHandle()',initHandle)
            // console.log('loginHandle()',loginHandle)
            // console.log('joinRoom()',joinRoom)
            audioIconAreaElement = document.querySelector('.jufengAudioIconArea')
            videoIconAreaElement = document.querySelector('.jufengVideoIconArea')
            initHandle()
            function createRequest() {
                const sentInfoJSON = JSON.stringify({
                    sessionId: sessionId,
                    roomId: joinSettings.roomId,
                    actionType: "createRequest",
                    from: 2
                });
                callService({
                    data: {
                        requestType: "videoMeetingEvent",
                        data: sentInfoJSON
                    },
                    success: data => {
                        console.log('videoMeetingEvent-data', data)
                    }
                }, true).fail(function (error) {
                    $F.alert(i18n.error.uploadFailed + 'createVideoRequest: ' + error);
                });
            }


            function trust() {
                window.open(clientEnv.server, '_blank');
            }

            function generateUniqueString(length) {
                const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
                var uniqueString = '';
                const charactersLength = characters.length;
                for (let i = 0; i < length; i++) {
                    const randomIndex = Math.floor(Math.random() * charactersLength);
                    uniqueString += characters.charAt(randomIndex);
                }
                return uniqueString;
            }


            /**
             * client
             */
            //初始化1
            function clientInit() {
                const clientInitParam = new JRTCClientInitParam();
                clientInitParam.appName = "JCCSample-H5";
                clientInitParam.server = clientEnv.server;
                clientInitParam.appKey = clientEnv.appKey;
                clienstState = ClientState.IDLE;

                client = JRTCClient.create({
                    onLogin: (result, reason) => {
                        console.log('onLogin result: ', result, ' reason: ', reason);

                    },
                    onLogout: (reason) => {
                        console.log('onLogout reason: ', reason);
                        // leave();

                    },
                    onClientStateChanged: (state, oldState) => {
                        console.log('onClientStateChanged state: ', state);
                        clienstState = state;
                        isLogin = state == ClientState.LOGINED || state == ClientState.LOGINING;

                        onClientStatusChanged(state);
                    },
                    onSDKEvent: (event) => {
                        console.log('onSDKEvent event: ', event);
                        if (event.errorCode && event.errorCode.length > 0 && event.errorCodeDetail && event.errorCodeDetail.length > 0) {
                            let content = "错误码:" + event.errorCode + "错误描述:" + event.errorCodeDetail;
                            appendErrorContent(content);
                        }
                    },
                    onOnlineMessageReceived: (message, userId) => {
                        showToast('收到来自 ' + userId + ' 发送的在线消息: ' + message);
                    },
                    onOnlineMessageSendResult: (result, operatorId) => {
                        let content = '发送';
                        content += result ? '成功' : '失败';
                        content += ' operatorId: ' + operatorId;
                        console.log(content);
                    }
                }, clientInitParam);
                JRTCTracking.setChannel("H5 channel");

                JRTCLog.localLogStore = logStore;
            }

            //初始化
            function mediaDeviceInit() {
                mediaDevice = JRTCMediaDevice.create({
                    onVolumeChanged: (volume, userId) => {
                        if (userId == null || userId == client.getUserId()) {
                            let progress = volumeMap['progress' + client.getUserId()];
                            if (progress) {
                                progress.value = volume / 100;
                            }
                        } else {
                            let progress = volumeMap['progress' + userId];
                            if (progress) {
                                progress.value = volume / 100;
                            }
                        }
                    },
                    onCameraUpdate: () => {
                        room.getUploadLocalVideo() &&  videoIconAreaElement.classList.add('videoSvgActive');
                    },
                    onAudioInputUpdate: () => {
                        room.getUploadLocalAudio() && audioIconAreaElement.classList.add('audioSvgActive');
                    }
                }, {});

                setTimeout(() => {
                    cameraList = mediaDevice.getCameras();

                    console.log('cameraList = ', cameraList);

                    if (cameraList.length > 0) {
                        roomSettings.currentCamera = cameraList[0];
                        console.log('currentCamera = ', roomSettings.currentCamera);
                    }

                    microphoneList = mediaDevice.getAudioInputs();

                    console.log('microphoneList:', microphoneList);

                    if (microphoneList.length > 0) {
                        roomSettings.currentMic = microphoneList[0];

                        console.log('roomSettings.currentMic:', roomSettings.currentMic);
                    }
                }, 500);


            }

            function initHandle() {
                $('.jufengMeeting.videoMeet', container).show();
                $('.jufengMeeting.videoMeet .video', container).show();
                $('.jufengMeeting.videoMeet .audio', container).hide();
                $('.jufengMeeting .video .titleBox .title').html('视频通话 '+ ` (${userName})`)
                if (isInitialized) {
                    if (isLogin) {
                        client.logout();
                    }
                    JRTCClient.destroy();
                    client = null;

                    JRTCMediaDevice.destroy();
                    mediaDevice = null;

                    if (isJoined) {
                        room.leave();
                    }
                    JRTCRoom.destroy();
                    room = null;
                } else {
                    clientInit();
                    mediaDeviceInit();
                    loginHandle()
                    joinRoom()
                }
                isInitialized = !isInitialized;
            }

            function downloadLog() {

                const blob = JRTCLog.getLogMessage(),
                    blobUrl = window.URL.createObjectURL(blob),
                    tempLink = document.createElement('a');

                tempLink.style.display = 'none';
                tempLink.href = blobUrl;
                tempLink.setAttribute('download', `H5 ${window.location.host}-${Date.now()}.log`);

                if (typeof tempLink.download === 'undefined') {
                    tempLink.setAttribute('target', '_blank');
                }

                document.body.appendChild(tempLink);
                tempLink.click();
                document.body.removeChild(tempLink);

                setTimeout(() => {
                    window.URL.revokeObjectURL(blobUrl);
                });
            }

            function clearLog() {
                JRTCLog.clearLogMessage();
            }

            function loginHandle() {
                if (isLogin) {
                    client.logout();
                    setTimeout(()=>{
                        initHandle()
                        $('.jufengMeeting', container).hide();
                    },800)

                } else {
                    clientInit();
                    let loginParam = new JRTCClientLoginParam();
                    loginParam.token = clientEnv.token;
                    loginParam.tokenType = clientEnv.tokenType;
                    client.setDisplayName(joinSettings.displayName);
                    client.login(joinSettings.userId, '123456', loginParam);
                }
            }

            function sendOnlineMessage() {
                client.sendOnlineMessage(onlineMessage.content, onlineMessage.userId);
            }

            /* page actions  */
            function startCamera() {
                console.log("startCamera");
                mediaDevice.startCamera();
            }

            function stopCamera() {
                console.log("stopCamera");
                mediaDevice.stopCamera();
            }

            function startCameraVideo() {
                return new Promise((resolve, reject) => {
                    console.log("startCameraVideo");

                    let viewId = 'local-video';
                    appendLocalVideo(viewId);

                    // mediaDevice.startCameraVideo(RenderType.RENDER_FULL_SCREEN).then((canvas) => {
                    //     let box = document.querySelector(`#${viewId}`);
                    //     console.log('box:', box);
                    //     if (!localCanvas || localCanvas.id != canvas.id) {
                    //         if (localCanvas) {
                    //             box?.removeChild(localCanvas.videoDivDOM);
                    //         }
                    //         localCanvas = canvas;
                    //         box?.appendChild(canvas.videoDivDOM);
                    //     }
                    // });

                    // 或者传入viewId和document
                    let box = document.querySelector(`#${viewId}`);
                    mediaDevice.startCameraVideo(renderType, box).then((canvas) => {
                        if (!canvas) {
                            showToast(`本地视频渲染失败`);
                        }

                        localCanvas = canvas;
                        resolve();
                    });
                })
            }

            function stopCameraVideo() {
                if (localCanvas != null) {
                    mediaDevice.stopVideo(localCanvas);
                }
            }

            function startLocalAudio() {
                return new Promise((resolve, reject) => {
                    mediaDevice.startAudioInput().then(() => {

                        resolve();
                    });
                })
            }

            // 处理设备切换
            function handleCameraChange() {
                let camera = roomSettings.currentCamera;
                mediaDevice.switchCamera(camera);
            }

            /**
             * Room 相关
             */

            function roomInit() {
                if (roomCallback == null) {
                    initRoomCallbacks();
                }

                const param = new JRTCRoomInitParam();
                param.roomServer = roomEnv.server;
                param.protocol = 'WEBRTC';

                const paramStr = param.toString();
                console.log('param: ', paramStr);
                room = JRTCRoom.create(client, mediaDevice, param, roomCallback);
            }

            function discoveryRoom() {
                const roomId = roomSettings.queryRoom.roomId;
                console.log('discoveryRoom roomId: ', roomId);
                let appKey = clientEnv.appKey;
                var oReq = new XMLHttpRequest();


                oReq.onload = function (e) {
                    let response = JSON.parse(oReq.response)
                    console.log('oReq.response 11', response);
                    let data = response.data;
                    if (data != null) {
                        if (data.exist != null && data.exist) {
                            showToast(`房间号：${roomId}已经存在`);
                        } else {
                            showToast(`房间号：${roomId}不存在`);
                        }
                    } else {
                        showToast("查询房间失败");
                    }
                }
                oReq.open("GET", `${roomEnv.server}/room/discovery?roomId=${roomId}&appKey=${appKey}`);
                oReq.send();
            }

            function joinRoom() {
                console.log('isJoined',isJoined)
                console.log('isLogin',isLogin)
                if (!isLogin) {
                    showToast('请先登录');
                    return;
                }

                if (isJoined) {
                    showToast('已经加入房间');
                    return;
                }
                if (room == null) {
                    roomInit();
                }


                // 设置媒体参数
                if (mediaSettings.isSelfDefined) {
                    joinSettings.videoDefinition = 0;
                    if (mediaSettings.captureResolution == 0) {
                        joinSettings.captureWidth = 360;
                        joinSettings.captureHeight = 640;
                    } else if (mediaSettings.captureResolution == 1) {
                        joinSettings.captureWidth = 480;
                        joinSettings.captureHeight = 720;
                    } else if (mediaSettings.captureResolution == 2) {
                        joinSettings.captureWidth = 720;
                        joinSettings.captureHeight = 1080;
                    }
                    if (!joinSettings.frameRate | joinSettings.frameRate <= 0) {
                        joinSettings.frameRate = 24;
                    }
                    joinSettings.svcResolution = mediaSettings.svcResolution;
                } else {
                    22
                    if (mediaSettings.maxResolution == 0) {
                        joinSettings.captureWidth = 360;
                        joinSettings.captureHeight = 640;
                        joinSettings.videoDefinition = VideoDefinition.FLUENCY_FRAME_HIGH;
                    } else if (mediaSettings.maxResolution == 1) {
                        joinSettings.captureWidth = 480;
                        joinSettings.captureHeight = 720;
                        joinSettings.videoDefinition = VideoDefinition.STANDARD_FRAME_HIGH;
                    } else if (mediaSettings.maxResolution == 2) {
                        joinSettings.captureWidth = 720;
                        joinSettings.captureHeight = 1080;
                        joinSettings.videoDefinition = VideoDefinition.HIGH_FRAME_HIGH;
                    }
                    joinSettings.frameRate = 24;
                    joinSettings.maxResolution = mediaSettings.maxResolution;
                }

                // 设置摄像头采集
                mediaDevice.setCameraProperty(joinSettings.captureWidth, joinSettings.captureHeight, joinSettings.frameRate);
                // 设置媒体类型，默认 ALL
                // mediaDevice.setSupportMediaType(MediaType.ALL);

                const param = new JRTCRoomJoinParam();
                param.enableRemoteRecord = true;
                param.capacity = joinSettings.capacity;
                param.password = joinSettings.password;
                param.svcResolution = joinSettings.svcResolution;
                param.maxResolution = joinSettings.maxResolution;
                param.maxFrameRate = joinSettings.frameRate;
                param.wholeRatio = joinSettings.wholeRatio;
                param.securityType = joinSettings.securityType;
                param.smoothMode = joinSettings.smoothMode;
                param.heartbeatTime = joinSettings.heartbeatTime;
                param.heartbeatTimeout = joinSettings.heartbeatTimeout;
                param.extraInfo = joinSettings.extraInfo;
                param.videoEncodeType = joinSettings.videoEncodeType;
                param.audioEncodeType = joinSettings.audioEncodeType;

                param.multiStream = joinSettings.isMultiStream;

                param.uploadLocalVideo = joinSettings.uploadLocalVideo;
                param.uploadLocalAudio = joinSettings.uploadLocalAudio;

                param.videoDefinition = joinSettings.videoDefinition;
                param.businessId = joinSettings.businessId;

                const paramStr = param.toString();
                console.log('param: ', paramStr);
                console.log('param.video: ', param.video);
                publishingAudio = param.uploadLocalAudio;
                publishingVideo = param.uploadLocalVideo;
                room.join(joinSettings.roomId, param);
                acceptRoomId ? '' : createRequest()
                $('.jufengMeeting.videoMeet .waitVideo', container).show();
                // setTimeout(function () {
                //     if (roomState == RoomState.JOINED) {
                //         startRemoteRecord()
                //     }
                // },3000)
            }

            function leave() {
                if (roomState == RoomState.JOINED || roomState == RoomState.JOINING) {
                    console.log('jufeng123456',room)
                    room.leave();

                }
            }

            function getParticipants() {
                const parts = room.getParticipants();
                console.log('parts: ', parts);
                roomSettings.participants = [];
                for (let index = 0; index < parts.length; index++) {
                    const element = parts[index];
                    roomSettings.participants.push(element);
                }
            }

            function subscribe(participant) {
                room.requestVideo(participant, {width: 360, height: 640}).then((result) => {
                    console.log('requestVideo result', result);
                    let userId = participant.userId;
                    if (result) {
                        let viewId = 'video-' + userId;
                        appendRemoteVideo(userId, false);
                        let box = document.getElementById(`${viewId}`);
                        const canvas = mediaDevice.startVideo(participant.streamUrl, renderType, result.mediaStream, box);
                        if (!canvas) {
                            if (joinSettings.isMultiStream) {
                                showToast(`${userId} 视频渲染失败`);
                            } else {
                                showToast("视频渲染失败");
                            }
                        }
                        mediaDevice.startAudioOutput(result.mediaStream, userId);
                    } else {
                        if (joinSettings.isMultiStream) {
                            showToast(`${userId} 视频流请求失败`);
                        } else {
                            showToast("视频流请求失败");
                        }
                    }
                });
            }

            // function publishVideo() {
            //     if (room.getUploadLocalVideo()) {
            //         return;
            //     }
            //     room.enableUploadVideoStream(true);
            //     publishingVideo = room.getUploadLocalVideo();
            // }
            //
            // function unPublishVideo() {
            //     if (!room.getUploadLocalVideo()) {
            //         return;
            //     }
            //     room.enableUploadVideoStream(false);
            //     publishingVideo = room.getUploadLocalVideo();
            // }

            // function publishAudio() {
            //     if (room.getUploadLocalAudio()) {
            //         return;
            //     }
            //     room.enableUploadAudioStream(true);
            //     publishingAudio = room.getUploadLocalAudio();
            // }
            //
            // function unPublishAudio() {
            //     if (!room.getUploadLocalAudio()) {
            //         return;
            //     }
            //     room.enableUploadAudioStream(false);
            //     publishingAudio = room.getUploadLocalAudio();
            // }

            function switchCamera() {
                mediaDevice.switchCamera();
            }

            function startRemoteRecord() {
                let param = new JRTCRecordRemoteParam();
                param.recordVideo = roomSettings.remoteRecordSettings.recordVideo;
                param.mergeMode = roomSettings.remoteRecordSettings.mergeMode;
                param.intelligentMergeMode = roomSettings.remoteRecordSettings.intelligentMergeMode;
                param.scsMergeMode = roomSettings.remoteRecordSettings.scsMergeMode;

                param.iBitrate = roomSettings.remoteRecordSettings.bitrate;
                param.frameRate = roomSettings.remoteRecordSettings.frameRate;

                param.videoWidth = roomSettings.remoteRecordSettings.videoWidth;
                param.videoHeight = roomSettings.remoteRecordSettings.videoHeight;

                console.log('kkkk startRemoteRecord waterMark:', roomSettings.remoteRecordSettings.waterMark);

                if (roomSettings.remoteRecordSettings.waterMark && roomSettings.remoteRecordSettings.waterMark.length > 0) {
                    let waterMarkMap = JSON.parse(roomSettings.remoteRecordSettings.waterMark);
                    if (waterMarkMap) {
                        param.watermarkTextMap = waterMarkMap;
                    }
                }

                console.log('kkkk startRemoteRecord param.watermarkTextMap:', param.watermarkTextMap);

                param.extraInfo = roomSettings.remoteRecordSettings.extraInfo;

                param.layoutType = roomSettings.remoteRecordSettings.layoutType;

                if (roomSettings.remoteRecordSettings.layoutArray && roomSettings.remoteRecordSettings.layoutArray.length > 0) {
                    let layoutArray = JSON.parse(roomSettings.remoteRecordSettings.layoutArray);
                    if (layoutArray) {
                        param.layoutArray = layoutArray;
                    }
                }

                param.fileName = roomSettings.remoteRecordSettings.fileName;
                param.splitFileSize = roomSettings.remoteRecordSettings.splitFileSize;
                room.enableRemoteRecord(true, param);
            }

            function stopRemoteRecord() {
                room.enableRemoteRecord(false, {});
            }

            function sendMessage() {
                // 消息内容
                if (roomSettings.sendMessage.content) {
                    let size = strSize(roomSettings.sendMessage.content);
                    if (size > 4096) {
                        showToast('消息内容过长，不能大于4KB');
                        return;
                    }
                }
                if (roomSettings.sendMessage.userId == '' || !roomSettings.sendMessage.userId) {
                    room.sendMessage(roomSettings.sendMessage.type, roomSettings.sendMessage.content, null);
                } else {
                    room.sendMessage(roomSettings.sendMessage.type, roomSettings.sendMessage.content, roomSettings.sendMessage.userId);
                }
            }

            function setRatio() {
                if (roomSettings.ratio > 0) {
                    room.setRatio(roomSettings.ratio);
                }
            }

            function snapshot() {
                localCanvas.snapshot()
                    .then(blob => {
                        document.getElementById('snapshot-preview').src = window.URL.createObjectURL(blob);
                    }).catch(e => {
                    console.error(e);
                    showToast('截图失败');
                });
            }

            function initRoomCallbacks() {
                roomCallback = {
                    onJoin: (result, reason, roomId) => {
                        console.log('onJoin result: ', result, reason, roomId);
                        if (result) {
                            publishingAudio = room.getUploadLocalAudio();
                            publishingVideo = room.getUploadLocalVideo();
                            getParticipants(); // 获取成员

                            if (joinSettings.isMultiStream) {
                                for (const p of roomSettings.participants) {
                                    if (p.userId !== client.getUserId()) {
                                        subscribe(p);//订阅已经在房间内的成员视频
                                    }
                                }
                            }

                            Promise.all(
                                // audio video
                                [startCameraVideo()
                                    , startLocalAudio()]

                                // audio only
                                // [startLocalAudio()]

                                // video only
                                // [startCameraVideo()]
                            ).then(() => {
                                console.log('sample enableUploadVideoStream');
                                getDevices();
                            });
                        }
                    },
                    onQuery: (operationId, result, reason, queryInfo) => {
                        console.log('onQuery operationId : result: reason: queryInfo: ', operationId, result, reason, queryInfo);
                        showToast('房间信息：' + queryInfo.toString());
                    },
                    onRoomStateChanged: (state, oldState) => {
                        console.log('onRoomStateChange state:%s oldState:%s', state, oldState);
                        roomState = state;
                        isJoined = state == RoomState.JOINED;
                        onRoomStatusChanged(state);
                    },
                    onLeave: (reason, roomId) => {
                        console.log('onLeave');
                        roomSettings.participants = [];
                        volumeMap = {};

                        roomSettings.recordState = RemoteRecordState.NONE;
                        roomSettings.enableRecord = false;
                        roomSettings.enableStopRecord = false;
                        publishingVideo = false;
                        publishingAudio = false;

                        clearInterval(statsInternalKey);

                        statsInfo = '';

                        clearStreamNode();
                        loginHandle()

                    },
                    onParticipantJoin: (participant) => {
                        console.log('onParticipantJoin participant: ', participant);
                        $('.jufengMeeting.videoMeet .waitAccept', container).hide();
                        if(participant._userId === 'MERGED__'){
                            if (roomState == RoomState.JOINED) {
                                startRemoteRecord()
                            }
                        }
                        if (joinSettings.isMultiStream) {
                            showToast('成员：' + participant.userId + '加入');
                            let exist = false;
                            for (const p of roomSettings.participants) {
                                if (p.userId === participant.userId) {
                                    exist = true;
                                    break;
                                }
                            }
                            if (!exist) {
                                subscribe(participant);
                            }
                        } else {
                            if (participant.userId == 'MERGED__') {
                                subscribe(participant);
                            } else {
                                showToast('成员：' + participant.userId + '加入');
                            }
                        }
                        getParticipants();
                    },
                    onParticipantLeft: (participant) => {
                        showToast('成员：' + participant.userId + '离开');
                        getParticipants();
                        removeRemoteVideo(participant.userId);
                        mediaDevice.stopAudioOutput(participant.userId);
                        volumeMap['progress' + participant.userId] = null;
                    },

                    onParticipantUpdate: (participant, changeParam) => {
                        console.log('onParticipantUpdate participant: ', participant, changeParam);
                        if (changeParam.netStatus) {
                            let netStatus = participant.netStatus;
                            if (netStatus == NetStatus.VERY_GOOD) {
                                // 网络非常好
                                console.log('网络非常好 ');
                            } else if (netStatus == NetStatus.GOOD) {
                                // 网络好
                            } else if (netStatus == NetStatus.BAD) {
                                // 网络一般
                            } else if (netStatus == NetStatus.NORMAL) {
                                // 网络较差
                            } else if (netStatus == NetStatus.DISCONNECTED) {
                                // 断开连接
                            }
                        }
                    },
                    onRoomPropertyChanged: (param) => {
                        console.log('onRoomPropertyChanged param: ', param);
                        if (param.remoteRecordState) {

                            roomSettings.recordState = room.getRemoteRecordState();
                            roomSettings.enableRecord = roomSettings.recordState == RemoteRecordState.READY;
                            roomSettings.enableStopRecord = roomSettings.recordState == RemoteRecordState.RUNNING;
                        }
                        if (param.screenShare) {
                            if (room.getShareUserId() && room.getShareUserId().length > 0) {
                                // 屏幕共享渲染
                                room.requestScreenVideo({width: 360, height: 640}).then((result) => {
                                    console.log('requestScreenVideo result', result);
                                    let userId = "screenShare";
                                    if (result) {
                                        let viewId = 'video-' + userId;
                                        appendRemoteVideo(userId, true);
                                        let box = document.getElementById(`${viewId}`);
                                        const canvas = mediaDevice.startVideo(result.streamUrl, renderType, result.mediaStream, box);
                                        screenShareCanvas = canvas;
                                        if (!canvas) {
                                            showToast('屏幕共享视频渲染失败');
                                        }
                                    } else {
                                        showToast(`屏幕共享视频流请求失败`);
                                    }
                                });
                            } else {
                                removeRemoteVideo('screenShare');
                                mediaDevice.stopVideo(screenShareCanvas);
                                screenShareCanvas = undefined;
                            }
                        }
                    },
                    onMessageReceived: (type, content, fromUserId) => {
                        if (type == 'JCRemoteDesktop') {
                            let desc = 'H5无法进行协作';
                            let descMap = {reason_code: 0, reason_desc: desc}
                            room.sendMessage('Decline', JSON.stringify(descMap), fromUserId);
                            return;
                        }

                        console.log('onMessageReceived type: ', type, content, fromUserId);
                        let message = "收到消息：" + content + " type：" + type + " fromUserId：" + fromUserId;
                        showToast(message);
                    }
                }
            }

            function isScreenShareParticipant(participant) {
                if (participant.userId === room.getCallId()) {
                    return true;
                }
                return false;
            }

            function getDevices() {
                setTimeout(() => {
                    cameraList = mediaDevice.getCameras();

                    console.log('cameraList = ', cameraList);

                    if (cameraList.length > 0) {
                        roomSettings.currentCamera = cameraList[0];
                        console.log('currentCamera = ', roomSettings.currentCamera);
                    }

                    microphoneList = mediaDevice.getAudioInputs();

                    console.log('microphoneList:', microphoneList);

                    if (microphoneList.length > 0) {
                        roomSettings.currentMic = microphoneList[0];

                        console.log('roomSettings.currentMic:', roomSettings.currentMic);
                    }
                }, 500);
            }

            /**
             * helper function
             */
            function showToast(msg, duration) {
                console.log(99999999999999,msg)
                toastList.push(msg);

                let length = toastList.length;
                let top = 5 * length + 30;

                duration = isNaN(duration) ? 3000 : duration;
                // var m = document.createElement('div');
                // m.innerHTML = msg;
                // m.style.cssText = `width:50%; min-width:180px; background:#000; opacity:0.5; height:auto;min-height: 30px; color:#fff; line-height:30px; text-align:center; border-radius:4px; position:fixed; top:${top}%; left:20%; z-index:999999;`
                // document.body.appendChild(m);
                //
                // setTimeout(function () {
                //     var d = 0.5;
                //     m.style.webkitTransition = '-webkit-transform ' + d + 's ease-in, opacity ' + d + 's ease-in';
                //     m.style.opacity = '0';
                //
                //     setTimeout(function () {
                //         document.body.removeChild(m);
                //         toastList.splice(0, 1);
                //     }, d * 1000);
                // }, duration);
            }


            function onClientStatusChanged(state) {
                if (state == ClientState.LOGINING) {
                    clientStateText = '登录中';
                } else if (state == ClientState.LOGINED) {
                    clientStateText = '已登录';
                } else if (state == ClientState.LOGOUTING) {
                    clientStateText = '登出中';
                } else {
                    clientStateText = '未登录';
                }
            }

            function onRoomStatusChanged(roomState) {
                if (roomState == RoomState.IDLE) {
                    roomStatus = 'idle';
                    roomStateText = '空闲';
                } else if (roomState == RoomState.JOINING) {
                    roomStatus = "joining";
                    roomStateText = '正在加入房间...';
                } else if (roomState == RoomState.JOINED) {
                    roomStatus = "joined";
                    roomStateText = '已经加入房间';
                } else if (roomState == RoomState.LEAVING) {
                    roomStatus = "leaving";
                    roomStateText = '正在离开房间...';
                }
            }

            function isScreenShareParticipant(participant) {
                if (participant.userId === room.getCallId()) {
                    return true;
                }
                return false;
            }

            function clearStreamNode() {
                const remote = document.getElementById("remote-video-container");
                if (remote != null) {
                    clearAllNode(remote);
                }

                const local = document.getElementById("local-video-container");
                if (local != null) {
                    clearAllNode(local);
                }
            }

            function clearAllNode(parentNode) {
                parentNode.innerHTML = '';
            }

            function appendErrorContent(content) {
                console.log('sdk-error', content)
                // let div = createDivDOM();
                // div.textContent = content;
                // let viewId = 'error-code-detail'
                // const box = document.querySelector(`#${viewId}`);
                // box.appendChild(div);
            }

            function createDivDOM() {
                const divDom = document.createElement('div');
                divDom.style.display = 'flex';
                divDom.style.margin = '0 auto';
                divDom.style.fontSize = '10px';
                return divDom;
            }

            function appendLocalVideo(vid) {

                let userId = client.getUserId();

                let viewId = 'local-video-container'
                let local_video_container = document.querySelector(`#${viewId}`);
                const figure = document.createElement('figure');
                figure.id = 'local_figure';

                figure.style.backgroundColor = 'red';
                figure.style.width = '100%';
                figure.style.margin = '0';

                let div = createDivDOM();
                div.style.width = '100%';
                div.style.height = '125px';
                div.id = vid;
                div.style.backgroundColor = 'rgba(0,0,0)';
                figure.appendChild(div);

                // let textDiv = createDivDOM();
                // textDiv.style.width = '180px';
                // textDiv.textContent = 'self';
                // textDiv.style.display = 'flex';
                // textDiv.style.justifyContent = 'center';
                // figure.appendChild(textDiv);

                local_video_container.appendChild(figure);
            }

            // $('.jufengMeeting .releaseVCall', container).click(function (e) {
            //     e.stopPropagation();
            //     leave()
            //     // let local_video_container = document.getElementById('local_figure');
            //     // // // let video = document.getElementById(`local-video`);
            //     // if (local_video_container) {
            //     //     body.removeChild(local_video_container);
            //     // }
            //
            //
            // });

            function appendRemoteVideo(userId, isScreenShare) {

                let viewId = 'remote-video-container'
                let remote_video_container = document.querySelector(`#${viewId}`);
                const figure = document.createElement('figure');

                figure.className = 'stream-wrapper';
                figure.id = 'figure-' + userId;

                figure.style.backgroundColor = 'red';
                figure.style.width = '100%';
                figure.style.margin = '0';

                let div = createDivDOM();
                div.style.width = '100%';
                div.style.height = '400px';
                div.id = 'video-' + userId;
                div.style.backgroundColor = 'rgba(0,0,0)';
                figure.appendChild(div);

                // if (!isScreenShare) {
                //     const progress = document.createElement('progress');
                //     progress.style.display = 'flex';
                //     progress.style.margin = '0 auto';
                //     volumeMap['progress' + userId] = progress;
                //     figure.appendChild(progress);
                // }

                // let textDiv = createDivDOM();
                // textDiv.style.width = '180px';
                // textDiv.textContent = userId;
                // textDiv.style.display = 'flex';
                // textDiv.style.justifyContent = 'center';
                // figure.appendChild(textDiv);

                remote_video_container.appendChild(figure);
            }

            function removeRemoteVideo(userId) {
                let viewId = 'remote-video-container';
                let remote_video_container = document.querySelector(`#${viewId}`);

                let videoViewId = 'figure-' + userId;
                let video = document.getElementById(`${videoViewId}`);
                if (video) {
                    remote_video_container.removeChild(video);
                }
            }

            function openFAQPage() {
                window.open(`../FAQ.html`);
            }

            function strSize(str, charset) {
                let total = 0;
                charset = charset?.toLowerCase() || '';
                for (i = 0; i < str.length; i++) {
                    let charCode = str.charCodeAt(i);
                    if (charset === 'utf-16' || charset === 'utf16') {
                        total += charCode <= 0xffff ? 2 : 4;
                    } else {
                        if (charCode <= 0x007f) {
                            total += 1;
                        } else if (charCode <= 0x07ff) {
                            total += 2;
                        } else if (charCode <= 0xffff) {
                            total += 3;
                        } else {
                            total += 4;
                        }
                    }
                }
                return total;
            }
            $('.jufengMeeting .caller .video .setCon .right .videoBox .jufengAudioIconArea', container).off('click')
            $('.jufengMeeting .caller .video .setCon .right .videoBox .jufengAudioIconArea', container).click(function () {
                if (room.getUploadLocalAudio()) {
                    room.enableUploadAudioStream(false);
                    publishingAudio = room.getUploadLocalAudio();
                    audioIconAreaElement.classList.remove('audioSvgActive');
                }else {
                    room.enableUploadAudioStream(true);
                    publishingAudio = room.getUploadLocalAudio();
                    audioIconAreaElement.classList.add('audioSvgActive');
                }

            })
            $('.jufengMeeting .caller .video .setCon .right .videoBox .jufengVideoIconArea', container).off('click')
            $('.jufengMeeting .caller .video .setCon .right .videoBox .jufengVideoIconArea', container).click(function () {
                if (room.getUploadLocalVideo()) {
                    room.enableUploadVideoStream(false);
                    publishingVideo = room.getUploadLocalVideo();
                    videoIconAreaElement.classList.remove('videoSvgActive');
                }else {
                    room.enableUploadVideoStream(true);
                    publishingVideo = room.getUploadLocalVideo();
                    videoIconAreaElement.classList.add('videoSvgActive');
                }
            })

        },
        unAnsweredVedioRequest: function (unAnsweredSessionId, unAnsweredRoomId) {
            const sentInfoJSON = JSON.stringify({
                sessionId: unAnsweredSessionId,
                roomId: unAnsweredRoomId,
                actionType: "noResponse",
                from: 2,
            });
            callService({
                data: {
                    requestType: "videoMeetingEvent",
                    data: sentInfoJSON
                },
                success: data => {
                }
            }, true).fail(function (e) {

            });
        },
        addVideoURlRequest: function (playUrl) {
            const sentInfoJSON = JSON.stringify({
                sessionId: sessionId,
                roomId: joinSettings.roomId,
                from: 2,
                videoPlayUrl:playUrl,
                videoDownloadUrl:playUrl
            });
            callService({
                data: {
                    requestType: "addVideoMeetingUrl",
                    data: sentInfoJSON
                },
                success: data => {
                    // Meet.clearSessionRequest(sessionId,roomId)
                }
            }, true).fail(function (error) {
                console.log(i18n.error.requestFailed + ',addVideoURlRequest:' + error);
            });
        },

        clearSessionRequest: function (clearSessionId, clearRoomId) {
            const sentInfoJSON = JSON.stringify({
                sessionId: clearSessionId.toString(),
                roomId: clearRoomId,
                actionType: "clearSession",
                from: 2,
            });
            callService({
                data: {
                    requestType: "videoMeetingEvent",
                    data: sentInfoJSON
                },
                success: data => {
                }
            }, true).fail(function (e) {
                $F.alert(i18n.error.requestFailed + ',clearSessionRequest:' + error);
            });
        },
        cancelRequest: function () {
            const sentInfoJSON = JSON.stringify({
                sessionId: sessionId,
                roomId: joinSettings.roomId,
                actionType: "cancelRequest",
                from: 2,
            });
            callService({
                data: {
                    requestType: "videoMeetingEvent",
                    data: sentInfoJSON
                },
                success: data => {
                    chatSendMessage(`${i18n.videoMeetingRecord.Cancel} [videoMeet]`, sessionId)
                    Meet.leaveRoom()
                }
            }, true).fail(function (error) {
                $F.alert(i18n.error.requestFailed + ',cancelRequest:' + error);
            });
        },
        levelRoomRequest: function () {
            const sentInfoJSON = JSON.stringify({
                sessionId: sessionId,
                roomId: joinSettings.roomId,
                actionType: "leaveRoom",
                from: 2,
            });
            callService({
                data: {
                    requestType: "videoMeetingEvent",
                    data: sentInfoJSON
                },
                success: data => {
                    $F.log("视频结束")
                    // Meet.clearSessionRequest(sessionId,joinSettings.roomId.toString())
                    Meet.leaveRoom()
                }
            }, true).fail(function (e) {

            });
        },
         generateUniqueString:function(length) {
        const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        var uniqueString = '';
        const charactersLength = characters.length;
        for (let i = 0; i < length; i++) {
            const randomIndex = Math.floor(Math.random() * charactersLength);
            uniqueString += characters.charAt(randomIndex);
        }
        return uniqueString;
    },
        obtainVideoRecord:function(url, params) {
            videoUrlIndex++
            $.ajax({
                url: url,
                type: 'POST',
                data: params.params,
                cache: false,
                xhrFields: {
                    withCredentials: true
                },
                success: function(res){
                    if(res.data.list&&res.data.list.length===0){
                        if(videoUrlIndex<=5){
                             setTimeout(function () {
                                Meet.obtainVideoRecord(url, params)
                            },2000)
                        }
                    }
                    if(res.data.list&&res.data.list.length>0){
                        let videoPlayUrl = res.data.list[0].url
                        Meet.addVideoURlRequest(videoPlayUrl)
                    }
                },
            })
        },
        leaveRoom: function () {
            videoUrlIndex = 0
            if(room){
            room && room.enableRemoteRecord(false, {});
            let roomCallId = room.getCallId()
                if(roomCallId) {
                // Meet.obtainVideoRecord(juFengApiPortUrl, {params: {"requestId": Meet.generateUniqueString(10), "action": "getUploadRecordInfo", "appKey":clientEnv.appKey,"callId":roomCallId}});
            Meet.obtainVideoRecord('https://localhost:448/jrtc', {params: {"requestId": Meet.generateUniqueString(10), "action": "getUploadRecordInfo", "appKey":clientEnv.appKey,"callId":roomCallId}});
            }
            if (roomState == RoomState.JOINED || roomState == RoomState.JOINING) {
                room.leave();
            }
            }
        },
    }

    return {
        loadSanTiMeet: Meet.init,
        leaveRoom: Meet.leaveRoom,
        levelRoomRequest: Meet.levelRoomRequest,
        clearSessionRequest: Meet.clearSessionRequest,
        cancelRequest: Meet.cancelRequest,
        unAnsweredVedioRequest:Meet.unAnsweredVedioRequest,
        obtainVideoRecord:Meet.obtainVideoRecord,
        generateUniqueString:Meet.generateUniqueString,
        addVideoURlRequest:Meet.addVideoURlRequest
    };

})
